//
//  DARisingMenu.m
//  DAKnowledge
//
//  Created by DreamArts on 16/4/28.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DARisingMenu.h"
#import "Utility.h"
#import "DAHeader.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

@interface DARisingMenu()<UIAlertViewDelegate, AVCaptureMetadataOutputObjectsDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>{
    UIVisualEffectView *effectView;
    MenuTouchBlocks menuBlock;
    NSArray *menuButtonTitles;
    NSArray *menuButtonImages;
    NSMutableArray *menuButtons;
    NSMutableArray *menuLabels;
    
    AVCaptureDevice *frontCamera;
    AVCaptureDevice *backCamera;
    AVCaptureSession *session;
    AVCaptureVideoPreviewLayer *previewLayer;
    AVCaptureInput *input;
    AVCaptureMetadataOutput *output;
}

@end

@implementation DARisingMenu
- (instancetype)initWithButtonTitles:(NSArray *)buttonTitles images:(NSArray *)buttonImages{
    self = [super initWithFrame:[[UIScreen mainScreen] bounds]];
    if(self){
        self.backgroundColor = [UIColor clearColor];
        [[[UIApplication sharedApplication] keyWindow]addSubview:self];
        menuButtonTitles = buttonTitles;
        menuButtonImages = buttonImages;
        [self configureMenuView];
    }
    return self;
}
/** 显示菜单 */
- (void)showOnTouchBlock:(MenuTouchBlocks)block{
    [self addSubview:effectView];
    [self riseButtons];
    NSString *scanCodeFindBook = NSLocalizedString(@"ScanTheBarCodeToFindBook", nil);
    effectView.alpha = 0;
    UILabel *launchLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.frame.size.width/2 -[ScanningView width]/2, orignToTop, [ScanningView width], [ScanningView width])];
    NSString *starCamera = NSLocalizedString(@"StartCamera", nil);
    launchLabel.text = starCamera;
    launchLabel.textColor = [UIColor lightGrayColor];
    launchLabel.textAlignment = NSTextAlignmentCenter;
    launchLabel.font = [UIFont systemFontOfSize:14];
    [effectView addSubview:launchLabel];
    [UIView animateWithDuration:0.2 animations:^{
        effectView.alpha = 1;
    }completion:^(BOOL finished) {
        menuBlock = block;
        [UIApplication sharedApplication].keyWindow.userInteractionEnabled = NO;
        NSString *mediaType = AVMediaTypeVideo;
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
            NSLog(@"相机权限受限");
            NSString *needOpenCamera = NSLocalizedString(@"needOpenCamera", nil);
            launchLabel.text = needOpenCamera;
            [UIApplication sharedApplication].keyWindow.userInteractionEnabled = YES;
            return;
        }
        if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
            [UIApplication sharedApplication].keyWindow.userInteractionEnabled = YES;
            return;
        }
        //  后台执行：
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [self initCapture];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self initOverView];
                launchLabel.frame = CGRectMake(self.frame.size.width/2 -[ScanningView width]/2, orignToTop + [ScanningView width]/2 +20, [ScanningView width] + 20, [ScanningView width]);
                launchLabel.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2, launchLabel.center.y);
                launchLabel.text = scanCodeFindBook;
                [UIApplication sharedApplication].keyWindow.userInteractionEnabled = YES;
            });
        });
        
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self initCapture];
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [self initOverView];
//                [launchLabel removeFromSuperview];
//            });
//        });
//        
//        
        
    }];
    
}

/** 配置页面 */
- (void)configureMenuView{
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight];
    /**  毛玻璃view 视图 */
    effectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    effectView.frame = self.frame;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissEffectView)];
    [effectView addGestureRecognizer:tap];
    effectView.userInteractionEnabled = YES;
    
    menuButtons = [NSMutableArray array];
    menuLabels = [NSMutableArray array];
    [menuButtonTitles enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(self.center.x - 40, self.bounds.size.height + 100, 80, 80);
        [button setImage:[UIImage imageNamed:[menuButtonImages objectAtIndex:idx]] forState:UIControlStateNormal];
        button.tag = idx;
        [button addTarget:self action:@selector(touchButton:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(self.center.x - 40, self.bounds.size.height + 100, 80, 20)];
        button.userInteractionEnabled = YES;
        label.text = menuButtonTitles[idx];
        label.textColor = [UIColor colorWithHexString:@"#757575"];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:14];
        [effectView addSubview:label];
        [effectView addSubview:button];
        [effectView bringSubviewToFront:button];
        [menuButtons addObject:button];
        [menuLabels addObject:label];
    }];
    
    UIImageView *knowledge = [[UIImageView alloc]initWithFrame:CGRectMake(0, self.frame.size.height - 120, 200 , 40 )];
    knowledge.image = [UIImage imageNamed:@"DAKnowledge@3x"];\
    knowledge.center = CGPointMake(effectView.center.x, knowledge.center.y);
    [effectView addSubview:knowledge];
    dispatch_async(dispatch_get_main_queue(), ^{
        NSURL *url = [[NSBundle mainBundle] URLForResource:@"6743.mp3" withExtension:nil];
        SystemSoundID soundID = 0;
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID);
        AudioServicesPlaySystemSound(soundID);
    });
}
/** 单击选项 */
- (void)touchButton:(id)sender{
    UIButton *button = (UIButton *)sender;
    menuBlock(button.tag);
    
    /** 菜单消失 */
    [UIView animateWithDuration:0.2 animations:^{
        effectView.alpha = 0;
    }completion:^(BOOL finished) {
        [effectView removeFromSuperview];
        [session stopRunning];
        [previewLayer removeFromSuperlayer];
        _overView.stopMoveLine = YES;
        [_overView removeFromSuperview];
        [self removeFromSuperview];
    }];
}

/** 菜单消失 */
-(void)dismissEffectView{
   
    [menuButtons enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *button = (UIButton *)obj;
        UILabel *label = [menuLabels objectAtIndex:idx];
        [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.4 initialSpringVelocity:0.4 options:UIViewAnimationOptionCurveEaseIn animations:^{
            //            CGFloat orignX;
            //            switch (idx%3) {
            //                case 0:
            //                    orignX = 20;
            //                    break;
            //                case 1:
            //                    orignX = [UIScreen mainScreen].bounds.size.width/2 - 40;
            //                    break;
            //                case 2:
            //                    orignX = [UIScreen mainScreen].bounds.size.width - 100;
            //                    break;
            //                default:
            //                    break;
            //            }
            button.frame = CGRectMake(self.center.x - 40, self.bounds.size.height + 100, 80, 80);
            label.frame = CGRectMake(self.center.x - 40, self.bounds.size.height + 100, 80, 20);
        } completion:^(BOOL finished) {
            
        }];
    }];
    [UIView animateWithDuration:0.2 animations:^{
        effectView.alpha = 0;
    }completion:^(BOOL finished) {
        [effectView removeFromSuperview];
        [session stopRunning];
        _overView.stopMoveLine = YES;
        [_overView removeFromSuperview];
        [self removeFromSuperview];
    }];
}

/** 按钮上升动画 */
- (void)riseButtons{
    [menuButtons enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *button = (UIButton *)obj;
        UILabel *label = [menuLabels objectAtIndex:idx];
        [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.4 initialSpringVelocity:0.4 options:UIViewAnimationOptionCurveEaseIn animations:^{
            CGFloat orignX;
            switch (idx%3) {
                case 0:
                    orignX = 20;
                    break;
                case 1:
                    orignX = [UIScreen mainScreen].bounds.size.width/2 - 40;
                    break;
                case 2:
                    orignX = [UIScreen mainScreen].bounds.size.width - 100;
                    break;
                default:
                    orignX = 0;
                    break;
            }
            button.frame = CGRectMake(orignX , ([UIScreen mainScreen].bounds.size.height / 2 + 100*(idx/3))+20, 80, 80);
            label.frame = CGRectMake(orignX, ([UIScreen mainScreen].bounds.size.height / 2 + 80 + 100*(idx/3))+20 , 80, 20);
        } completion:^(BOOL finished) {
            
        }];
    }];
    
}

- (void)initOverView{
    _overView = [[ScanningView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height / 2)];
    _overView.stopMoveLine = NO;
    [effectView addSubview:_overView];
}

- (void)initCapture{
    
    session = [[AVCaptureSession alloc]init];
    [session setSessionPreset:AVCaptureSessionPresetHigh];
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *camera in devices) {
        if (camera.position == AVCaptureDevicePositionFront) {
            frontCamera = camera;
        }else{
            backCamera = camera;
        }
    }
    
    input = [AVCaptureDeviceInput deviceInputWithDevice:backCamera error:nil];
    output = [[AVCaptureMetadataOutput alloc]init];
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    if ([session canAddInput:input]) {
        [session addInput:input];
    }
    if ([session canAddOutput:output]) {
        [session addOutput:output];
    }
    NSLog(@"%f", backCamera.activeFormat.videoMaxZoomFactor);
    
    output.metadataObjectTypes = @[AVMetadataObjectTypeEAN13Code,
                                   AVMetadataObjectTypeEAN8Code,
                                   AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeQRCode];
    
    previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
    previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    previewLayer.frame = CGRectMake(self.frame.size.width/2 -[ScanningView width]/2, orignToTop, [ScanningView width], [ScanningView width]);
    [effectView.layer addSublayer:previewLayer];
    
     [session startRunning];
    CGFloat screenHeight = ScreenSize.height;
    CGFloat screenWidth = ScreenSize.width;
    
    CGRect cropRect = CGRectMake((screenWidth - TransparentArea([ScanningView width], [ScanningView height]).width) / 2,
                                 (screenHeight - TransparentArea([ScanningView width], [ScanningView height]).height) / 2,
                                 TransparentArea([ScanningView width], [ScanningView height]).width,
                                 TransparentArea([ScanningView width], [ScanningView height]).height);
    
    [output setRectOfInterest:CGRectMake(cropRect.origin.y / screenHeight,
                                         cropRect.origin.x / screenWidth,
                                         cropRect.size.height / screenHeight,
                                         cropRect.size.width / screenWidth)];
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    NSString *stringValue;
    NSDictionary *dicValue;
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *metadateObject = [metadataObjects objectAtIndex:0];
        NSLog(@"%@",metadateObject.type);
        if([metadateObject.type isEqual:@"org.iso.QRCode"]){
            NSData *jsonData = [metadateObject.stringValue dataUsingEncoding:NSUTF8StringEncoding];
            NSError *err;
            dicValue = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                options:NSJSONReadingMutableContainers
                                                                  error:&err];
            [self readingFinshedWithDic:dicValue];
        }else{
            stringValue = metadateObject.stringValue;
            [self readingFinshedWithMessage:stringValue];
        }
    }
}

- (void)readingFinshedWithMessage:(NSString *)msg{
    if (msg) {
        //处理委托
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:msg,@"code", nil];
        [self.delegate didScanFinished:dic type:CodeTypeNormal];
    }else{
        
    }
}

- (void)readingFinshedWithDic:(NSDictionary *)msg{
    if (msg) {
        //处理委托
        [self.delegate didScanFinished:msg type:CodeTypeQR];
    }else{
        
    }
}

@end

#pragma ScanningView

@interface ScanningView ()
@property (strong, nonatomic) UIView *line;

@property (assign, nonatomic) CGFloat origin;
@property (assign, nonatomic) BOOL isReachEdge;


@property (assign , nonatomic) ScaningLineMoveMode lineMoveMode;
@property (assign, nonatomic) ScaningLineMode lineMode;
@property (assign, nonatomic) ScaningWarningTone warninTone;

@end


@implementation ScanningView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self initConfig];
    }
    return self;
}


- (void)initConfig{
    
    self.backgroundColor = [UIColor clearColor];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(viewWillDisappear:) name:@"ViewWillDisappearNotification" object:nil];
    
    self.lineMode = ScaningLineModeGrid;
    self.lineMoveMode = ScaningLineMoveModeDown;
    
    self.line = [self creatLine];
    [self addSubview:self.line];
    [self starMove];
    
}

- (UIView *)creatLine{
    
    if (_lineMoveMode == ScaningLineMoveModeNone) return nil;
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(ScreenSize.width*.5 - TransparentArea([ScanningView width], [ScanningView height]).width*.5, orignToTop, TransparentArea([ScanningView width], [ScanningView height]).width, 2)];
    if (_lineMode == ScaningLineModeDeafult) {
        line.backgroundColor = LineColor;
        self.origin = line.frame.origin.y;
    }
    
    if (_lineMode == ScaningLineModeImge) {
        line.backgroundColor = [UIColor clearColor];
        self.origin = line.frame.origin.y;
        UIImageView *v = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"line@2x.png"]];
        v.contentMode = UIViewContentModeScaleAspectFill;
        v.frame = CGRectMake(0, 0, line.frame.size.width, line.frame.size.height);
        [line addSubview:v];
    }
    
    if (_lineMode == ScaningLineModeGrid) {
        line.clipsToBounds = YES;
        CGRect frame = line.frame;
        frame.size.height = TransparentArea([ScanningView width], [ScanningView height]).height;
        line.frame = frame;
        UIImageView *iv = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"scan_net@2x.png"]];
        iv.frame = CGRectMake(0, orignToTop, line.frame.size.width, TransparentArea([ScanningView width], [ScanningView height]).height);
        [line addSubview:iv];
    }
    
    return line;
}

- (void)starMove{
    if (_lineMode == ScaningLineModeDeafult) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.0125 target:self selector:@selector(showLine) userInfo:nil repeats:YES];
        [self.timer fire];
    }
    
    if (_lineMode == ScaningLineModeImge) {
        
        [self showLine];
    }
    
    if (_lineMode == ScaningLineModeGrid) {
        
        UIImageView *iv = _line.subviews[0];
        [UIView animateWithDuration:1.5 delay:0.1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            iv.transform = CGAffineTransformTranslate(iv.transform, 0, TransparentArea([ScanningView width], [ScanningView height]).height);
        } completion:^(BOOL finished) {
            iv.frame = CGRectMake(0, -TransparentArea([ScanningView width], [ScanningView height]).height, _line.frame.size.width, TransparentArea([ScanningView width], [ScanningView height]).height);
            if(!self.stopMoveLine){
                [self starMove];
            }
        }];
    }
}

- (void)showLine{
    
    if (_lineMode == ScaningLineModeDeafult) {
        CGRect frame = self.line.frame;
        self.isReachEdge?(frame.origin.y -= LineMoveSpeed):(frame.origin.y += LineMoveSpeed);
        self.line.frame = frame;
        
        UIView *shadowLine = [[UIView alloc]initWithFrame:self.line.frame];
        shadowLine.backgroundColor = self.line.backgroundColor;
        [self addSubview:shadowLine];
        [UIView animateWithDuration:LineShadowLastInterval animations:^{
            shadowLine.alpha = 0;
        } completion:^(BOOL finished) {
            [shadowLine removeFromSuperview];
        }];
        
        if (_lineMoveMode == ScaningLineMoveModeDown) {
            if (self.line.frame.origin.y - self.origin >= TransparentArea([ScanningView width], [ScanningView height]).height) {
                [self.line removeFromSuperview];
                CGRect frame = self.line.frame;
                frame.origin.y = ScreenSize.height*.5 - TransparentArea([ScanningView width], [ScanningView height]).height*.5;
                self.line.frame = frame;
            }
            
        }else if(_lineMoveMode==ScaningLineMoveModeUpAndDown){
            if (self.line.frame.origin.y - self.origin >= TransparentArea([ScanningView width], [ScanningView height]).height) {
                self.isReachEdge = !self.isReachEdge;
            }else if (self.line.frame.origin.y == self.origin){
                self.isReachEdge = !self.isReachEdge;
            }
        }
    }
    
    if (_lineMode == ScaningLineModeImge) {
        [self imagelineMoveWithMode:_lineMoveMode];
    }
}

- (void)imagelineMoveWithMode:(ScaningLineMoveMode)mode{
    
    [UIView animateWithDuration:2 animations:^{
        CGRect frame = self.line.frame;
        frame.origin.y +=  TransparentArea([ScanningView width], [ScanningView height]).height-2;
        self.line.frame = frame;
    } completion:^(BOOL finished) {
        if (mode == ScaningLineMoveModeDown) {
            CGRect frame = self.line.frame;
            frame.origin.y = ScreenSize.height*.5 - TransparentArea([ScanningView width], [ScanningView height]).height*.5;
            self.line.frame = frame;
            [self imagelineMoveWithMode:mode];
        }else{
            [UIView animateWithDuration:2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                CGRect frame = self.line.frame;
                frame.origin.y = ScreenSize.height*.5 - TransparentArea([ScanningView width], [ScanningView height]).height*.5;
                self.line.frame = frame;
            } completion:^(BOOL finished) {
                [self imagelineMoveWithMode:mode];
            }];
        }
    }];
    
}

- (void)drawRect:(CGRect)rect{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 40/255.0, 40/255.0, 40/255.0, 0);
    CGContextFillRect(context, rect);
    NSLog(@"%@", NSStringFromCGSize(TransparentArea([ScanningView width], [ScanningView height])));
    CGRect clearDrawRect = CGRectMake(rect.size.width / 2 - TransparentArea([ScanningView width], [ScanningView height]).width / 2,
                                      orignToTop,
                                      TransparentArea([ScanningView width], [ScanningView height]).width,TransparentArea([ScanningView width], [ScanningView height]).height);
    
    CGContextClearRect(context, clearDrawRect);
    [self addWhiteRect:context rect:clearDrawRect];
    [self addCornerLineWithContext:context rect:clearDrawRect];
}

- (void)addWhiteRect:(CGContextRef)ctx rect:(CGRect)rect {
    CGContextStrokeRect(ctx, rect);
    CGContextSetRGBStrokeColor(ctx, 1, 1, 1, 1);
    CGContextSetLineWidth(ctx, 0.8);
    CGContextAddRect(ctx, rect);
    CGContextStrokePath(ctx);
}

- (void)addCornerLineWithContext:(CGContextRef)ctx rect:(CGRect)rect{
    
    //画四个边角
    CGContextSetLineWidth(ctx, 2);
    CGContextSetRGBStrokeColor(ctx, 83 /255.0, 239/255.0, 111/255.0, 1);//绿色
    
    //左上角
    CGPoint poinsTopLeftA[] = {
        CGPointMake(rect.origin.x+0.7, rect.origin.y),
        CGPointMake(rect.origin.x+0.7 , rect.origin.y + 15)
    };
    CGPoint poinsTopLeftB[] = {CGPointMake(rect.origin.x, rect.origin.y +0.7),CGPointMake(rect.origin.x + 15, rect.origin.y+0.7)};
    [self addLine:poinsTopLeftA pointB:poinsTopLeftB ctx:ctx];
    //左下角
    CGPoint poinsBottomLeftA[] = {CGPointMake(rect.origin.x+ 0.7, rect.origin.y + rect.size.height - 15),CGPointMake(rect.origin.x +0.7,rect.origin.y + rect.size.height)};
    CGPoint poinsBottomLeftB[] = {CGPointMake(rect.origin.x , rect.origin.y + rect.size.height - 0.7) ,CGPointMake(rect.origin.x+0.7 +15, rect.origin.y + rect.size.height - 0.7)};
    [self addLine:poinsBottomLeftA pointB:poinsBottomLeftB ctx:ctx];
    //右上角
    CGPoint poinsTopRightA[] = {CGPointMake(rect.origin.x+ rect.size.width - 15, rect.origin.y+0.7),CGPointMake(rect.origin.x + rect.size.width,rect.origin.y +0.7 )};
    CGPoint poinsTopRightB[] = {CGPointMake(rect.origin.x+ rect.size.width-0.7, rect.origin.y),CGPointMake(rect.origin.x + rect.size.width-0.7,rect.origin.y + 15 +0.7 )};
    [self addLine:poinsTopRightA pointB:poinsTopRightB ctx:ctx];
    
    CGPoint poinsBottomRightA[] = {CGPointMake(rect.origin.x+ rect.size.width -0.7 , rect.origin.y+rect.size.height+ -15),CGPointMake(rect.origin.x-0.7 + rect.size.width,rect.origin.y +rect.size.height )};
    CGPoint poinsBottomRightB[] = {CGPointMake(rect.origin.x+ rect.size.width - 15 , rect.origin.y + rect.size.height-0.7),CGPointMake(rect.origin.x + rect.size.width,rect.origin.y + rect.size.height - 0.7 )};
    [self addLine:poinsBottomRightA pointB:poinsBottomRightB ctx:ctx];
    CGContextStrokePath(ctx);
}

- (void)addLine:(CGPoint[])pointA pointB:(CGPoint[])pointB ctx:(CGContextRef)ctx {
    CGContextAddLines(ctx, pointA, 2);
    CGContextAddLines(ctx, pointB, 2);
}

+ (NSInteger)width{
    if (Iphone4||Iphone5) {
        return Iphone45ScanningSize_width;
    }else if(Iphone6){
        return Iphone6ScanningSize_width;
    }else if(Iphone6Plus){
        return Iphone6PlusScanningSize_width;
    }else{
        return Iphone45ScanningSize_width;
    }
}

+ (NSInteger)height{
    if (Iphone4||Iphone5) {
        return Iphone45ScanningSize_height;
    }else if(Iphone6){
        return Iphone6ScanningSize_height;
    }else if(Iphone6Plus){
        return Iphone6PlusScanningSize_height;
    }else{
        return Iphone45ScanningSize_height;
    }
}


- (void)viewWillDisappear:(NSNotification *)noti{
    [self.timer invalidate];
    self.timer = nil;
}
- (void)dealloc{
    NSLog(@"%@dead", self.description);
}

@end
